package com.boyinet.demo.pipelineleakage.controller;

import com.boyinet.demo.pipelineleakage.exception.UnauthorizedException;
import com.google.common.collect.ImmutableMap;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;


/**
 * @author lengchunyun
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = UnauthorizedException.class)
    public ResponseEntity<ErrorResponse<Map<String, Boolean>>> unAuthorized() {
        ImmutableMap<String, Boolean> data = ImmutableMap.<String, Boolean>builder()
                .put("isLogin", false)
                .build();
        ErrorResponse<Map<String, Boolean>> body = ErrorResponse
                .data("请先登录！", data);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
    }


    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<ErrorResponse<Void>> exception(Exception e) {
        ErrorResponse<Void> body = ErrorResponse.msg(e.getMessage());
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(body);
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class ErrorResponse<T> {
        private Boolean success;
        private T data;
        private String errorCode;
        private String errorMessage;
        private Byte showType;

        public static ErrorResponse<Void> msg(String errorMessage) {
            ErrorResponse<Void> response = new ErrorResponse<>();
            response.setSuccess(false);
            response.setErrorCode("500");
            response.setErrorMessage(errorMessage);
            response.setShowType((byte) 2);
            return response;
        }

        public static <T> ErrorResponse<T> data(String errorMessage, T data) {
            return new ErrorResponse<>(false, data, "500", errorMessage, (byte) 2);
        }
    }
}
